package com.beone.admin.utils;

import com.base.common.util.BaseStringUtils;
import com.base.common.util.DateUtil;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Title
 * @Author 秦波
 * @Version 1.0 on 2019/4/814:42
 * @Copyright 长笛龙吟
 */
public class DES3EncryptAndDecrypt {

    private static final String ALGORITHM = "DESede";
    private static final String DES3_KEY ="HUNANSHIFANDAXUEZIZHUDAYINGXITONG"; //FinanceP2PApplicationConfig.getInstance().getProperty("APP.API.DES3_KEY");
    private static Logger logger = LoggerFactory.getLogger(DES3EncryptAndDecrypt.class);
    public static final String ERROR_MSG="鉴权失败,请确认是否按照正确方式进行sign生成";


    /**
     * 检查签名是否正确
     * @param sourceSign 源签名
     * @param params 现有参数
     * @return
     */
    public static boolean isCheckSign(String sourceSign,String params){
        String sign=encryptDES3Mode(params);
        logger.info("源sign:"+sourceSign);
        logger.info("生成sign:"+sign);
        return BaseStringUtils.equals(sourceSign,sign);
    }

    /**
     * 数据加密
     * @param src
     * @return
     * @throws Exception
     */
    public static String encryptDES3Mode(String src) {
        //src=src+ DateUtil.date2String("yyyyMMddHHmm");
        logger.info("参数串"+src);
        Cipher cipher = null;
        try {
            cipher = getCipher(Cipher.ENCRYPT_MODE);
            return new String(Base64.encodeBase64(cipher.doFinal(src.getBytes("UTF-8"))));
        } catch (Exception e) {
            logger.error("encryptDES3Mode 数据加密异常！", e);
        }
        return src;
    }

    private static Cipher getCipher(int encryptMode) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        DESedeKeySpec desKeySpec = new DESedeKeySpec(DES3_KEY.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        cipher.init(encryptMode, secretKey);
        return cipher;
    }

    /**
     * 数据解密
     * @param src
     * @return
     * @throws Exception
     */
    public static String  decryptDES3Mode(String src) {
        Cipher cipher = null;
        try {
            cipher = getCipher(Cipher.DECRYPT_MODE);
            byte [] dd=cipher.doFinal(Base64.decodeBase64(src.getBytes("UTF-8")));
            return new String(dd,"UTF-8");
        } catch (Exception e) {
            logger.error("decryptDES3Mode 数据解密异常！", e);
        }
        return src;
    }

    //写一个md5加密的方法
    public static String md5(String plainText) {
        //定义一个字节数组
        byte[] secretBytes = null;
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            //对字符串进行加密
            md.update(plainText.getBytes());
            //获得加密后的数据
            secretBytes = md.digest();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有md5这个算法！");
        }
        //将加密后的数据转换为16进制数字
        String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
        // 如果生成数字未满32位，需要前面补0
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }


    public static void main(String[] args) {
        //System.out.println(DES3EncryptAndDecrypt.encryptDES3Mode("周玮201630021091xjzmzn201904101223"))

        System.out.println(decryptDES3Mode("BAHn5RO0YrST13lVshsa8U1Wg+F/fsljK0h1IwNifTKffXj+k1yBBw=="));;
        System.out.println(decryptDES3Mode("BAHn5RO0YrST13lVshsa8U1Wg+F/fsljK0h1IwNifTIogguOOlfGVQ=="));
       /* System.out.println(DES3EncryptAndDecrypt.decryptDES3Mode("2H77JXEg2cMl0GRXG4ctw9bG1qpscpV9BunzNNyrvogLxjxS/WzghA=="));
        System.out.println(DES3EncryptAndDecrypt.md5("0f8e7ef1-da22-495a-9058-4a8b57f5039c2222222222222222222"));*/
      //  System.out.println(DES3EncryptAndDecrypt.encryptDES3Mode("1"));

        //System.out.println(DES3EncryptAndDecrypt.decryptDES3Mode("TqFC1cSWgh90od3ydiQwtxrhtqh7uf3h5xljz+LExQSopwUi1XWEXYDPzn+UV6GB56RH//xY7J+bFq7JiW25rQvGPFL9bOCE"));
    }
}
